package com.lushuan.ch11_springboot_test.demo.collection;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ConcurrentHashMapExample {
    public static void main(String[] args) {
        // 创建一个线程安全的ConcurrentHashMap
        ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(5);

        // 使用多个线程并发写入数据
        for (int i = 0; i < 5; i++) {
            final int index = i;
            executorService.execute(() -> {
                String key = "key" + index;
                Integer value = index;

                // 插入数据（线程安全）
                map.put(key, value);

                System.out.println(Thread.currentThread().getName() + " put key: " + key + ", value: " + value);

                // 更新数据（使用CAS机制避免数据冲突）
                map.compute(key, (k, v) -> v == null ? 1 : v + 1);
                System.out.println(Thread.currentThread().getName() + " updated key: " + key + ", new value: " + map.get(key));
            });
        }

        // 关闭线程池
        executorService.shutdown();
    }
}

